//
//  ConsultDetail.m
//  HappyStore
//
//  Created by 王佐元聪 on 16/5/27.
//  Copyright © 2016年 LLJ. All rights reserved.
//

#import "ConsultDetail.h"
#import "LoveData.h"
#import "PinLunCell.h"
#import "PinLunVC.h"

static NSString *PinLun = @"PinLunCell";

@interface ConsultDetail ()<UITableViewDataSource,UITableViewDelegate,UIWebViewDelegate>
//@property (weak, nonatomic) UILabel *titleLabel;
//
//@property (weak, nonatomic) UILabel *timeLabel;

@property (assign, nonatomic) CGFloat numheight;

@property (weak, nonatomic) IBOutlet UITextField *textField;
@property (strong, nonatomic) LoveData *loveData;
@property (strong, nonatomic) NSMutableArray *commentsList;

@property (assign, nonatomic) NSInteger pagge;


@property (weak, nonatomic) IBOutlet UIButton *zanButton;

@property (weak, nonatomic) IBOutlet UIButton *collectButton;


@property (weak, nonatomic) IBOutlet UITextField *sendPinLun;

@property (weak, nonatomic) IBOutlet UIWebView *webView;
@property (strong, nonatomic) UIView *titleView;
@property (strong, nonatomic) UITableView *tableview;

@property (strong, nonatomic) NSDictionary *dicData;//数据源

@property (strong, nonatomic) NSString *isFocus;//判断关注非关注
@property (strong, nonatomic) NSString *isZan;
@property (strong, nonatomic) NSString *javaScriptString;
@property (assign, nonatomic) CGFloat didWebHeight;

@property (nonatomic) BOOL isRemove;
@end

@implementation ConsultDetail




-(UITableView *)tableview{
    if (!_tableview) {
        _tableview = [[UITableView alloc] init];
    }
    return _tableview;
}


-(NSMutableArray *)commentsList{
    if (!_commentsList) {
        _commentsList = [NSMutableArray array];
    }
    return _commentsList;
}


-(NSDictionary *)dicData{
    if (!_dicData) {
        _dicData = [NSDictionary dictionary];
    }
    return _dicData;
}



- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    if (!self.isRemove) {
        self.isRemove = YES;
        [_loveData removeObserver:self forKeyPath:@"focusNumber" context:@"1"];
        [_loveData removeObserver:self forKeyPath:@"isfocus" context:@"2"];
    }
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //解决黑条
    self.webView.opaque = NO;
    self.webView.backgroundColor = [UIColor clearColor];
    self.tabBarController.tabBar.hidden = YES;
    //导航条都透明度
    self.navigationController.navigationBar.translucent = NO;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"白色背景"] forBarMetrics:UIBarMetricsDefault];
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.webView.hidden = YES;
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 190, 44)];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.font = [UIFont systemFontOfSize:19];
    titleLabel.text = @"详情";
    titleLabel.textColor = RGB(45, 45, 45);
    titleLabel.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = titleLabel;

    //设置返回按钮
    UIBarButtonItem *leftItem = [UIBarButtonItem itemWithTarget:self action:@selector(leftBarButtonItemClick) image:@"返回" highImage:@"返回"];
    self.navigationItem.leftBarButtonItem = leftItem;
    self.webView.scrollView.alwaysBounceVertical = NO;
    self.pagge = 1;
    [self startNetWork];
    [self setupTitleView];
    
    //开启侧滑
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
}

-(void)leftBarButtonItemClick{
    [self.navigationController popViewControllerAnimated:YES];
}


//设置tableView
-(void)setupTableView{
    
     self.tableview.frame = CGRectMake(0, self.webView.scrollView.contentSize.height, self.webView.width, self.tableview.height);
    self.webView.scrollView.contentInset = UIEdgeInsetsMake(self.numheight-50, 0, self.tableview.height, 0);
    self.tableview.scrollEnabled = NO;
    
    [self.webView.scrollView addSubview:self.tableview];
    
    //
    [self.tableview reloadData];
    //集成下拉加载更多
    [self setupDownRefresh];
}
#pragma mark - 设置title和time
- (void)setupTitleView{
    UILabel *titleLabe = [[UILabel alloc] init];
    titleLabe.text = self.titleStr;
    titleLabe.numberOfLines = 0;
    titleLabe.lineBreakMode = NSLineBreakByWordWrapping;
    titleLabe.textAlignment = NSTextAlignmentLeft;
    UIFont *font = [UIFont fontWithName:@"Arial" size:20];
    titleLabe.font = font;
    titleLabe.textColor = [UIColor blackColor];
    //设置行间距
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:titleLabe.text];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:8];
    
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, titleLabe.text.length)];
    
    CGSize constranint = CGSizeMake(screenW-8, MAXFLOAT);
    CGSize size = [titleLabe sizeThatFits:constranint];
    
    titleLabe.frame = CGRectMake(8, 24, size.width, size.height);
    
    
    
    UILabel *timeLabel = [[UILabel alloc] init];
    NSString *str = [self.timeStr substringWithRange:NSMakeRange(10, 6) ];
    
    NSString *str1 = [self.timeStr substringToIndex:10];
    timeLabel.text= str1;
    
    
    timeLabel.font = [UIFont fontWithName:@"Arial" size:12];
    timeLabel.textColor = [UIColor lightGrayColor];
    
    timeLabel.frame = CGRectMake(10, titleLabe.y+titleLabe.height+8, 80, 13);
    
    UILabel *timefoo = [[UILabel alloc] initWithFrame:CGRectMake(timeLabel.width, timeLabel.y, 50, 13)];
    
    timefoo.font = [UIFont fontWithName:@"Arial" size:12];
    timefoo.textColor = [UIColor lightGrayColor];
    timefoo.text = str;
    
    
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0,-timeLabel.height-titleLabe.height-38 + 50, screenW, titleLabe.height + timeLabel.height +38)];
    self.numheight = view.height;
    [view addSubview:timefoo];
    [view addSubview:titleLabe];
    [view addSubview:timeLabel];
    
    self.webView.scrollView.contentInset = UIEdgeInsetsMake(view.frame.size.height - 50, 0, 0, 0);
    self.titleView = view;
//    [self.webView.scrollView addSubview:view];

    
    
}
- (void)loadWebView{
    
    NSURL *url = [NSURL URLWithString:self.dicData[@"description"]];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];

}


-(void)setupDownRefresh{
    
    
    self.tableview.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.pagge +=1;
        //加载更多评论
        [self getMorePingLun];
    }];
}

#pragma mark - 网页完成加载
-(void)webViewDidFinishLoad:(UIWebView *)webView{
    self.didWebHeight = webView.scrollView.contentSize.height;
    [self.webView.scrollView addSubview:self.titleView];
//    [self setupTitleView];
    
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    self.tableview.bounces = NO;
    [self setupTableView];
    [self.tableview reloadData];
    //获取p标签的HTML元素
    for (int i = 0; i < 20; i++) {
        NSString *jsStr = [NSString stringWithFormat:@"document.getElementsByTagName(\"p\")[%d].innerHTML",i];
        NSString *thisBodyText = [webView stringByEvaluatingJavaScriptFromString:jsStr];
        
        //提取thisBodyText中文字
        NSString *textStr = [self handleStringWithString:thisBodyText];
        
        if (textStr.length >= 30) {//选取长度大于30的
            self.javaScriptString = textStr;
            break;
        }
    }
    //处理“下载app的广告”
    NSString *downloadHeaderJSStr = @"document.getElementById(\"top-app-layer\").style.visibility=\"hidden\"";
    [webView stringByEvaluatingJavaScriptFromString:downloadHeaderJSStr];
    [self performSelector:@selector(btnDismiss) withObject:nil afterDelay:0.4f];
}
- (void)btnDismiss{
    self.webView.hidden = NO;
}
//去除字符串中用括号括住的位置
-(NSString *)handleStringWithString:(NSString *)str{
    
    NSMutableString * muStr = [NSMutableString stringWithString:str];
    while (1) {
        NSRange range = [muStr rangeOfString:@"<"];
        NSRange range1 = [muStr rangeOfString:@">"];
        if (range.location != NSNotFound) {
            NSInteger loc = range.location;
            NSInteger len = range1.location - range.location;
            [muStr deleteCharactersInRange:NSMakeRange(loc, len + 1)];
        }else{
            break;
        }
    }
    
    return muStr;
}
- (void)startNetWork
{
    [self showRoundProgressWithTitle:@"请稍后..."];
    
    NSMutableDictionary *muDicParameters = [NSMutableDictionary dictionary];
    //    userId=当前登录用户id&projectId=项目id
    [muDicParameters setObject:self.projectId forKey:@"id"];
    if ([USER_DEFAULTS objectForKey:@"userid"]!=nil) {
        [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"userid"] forKey:@"userId"];
    }
    
    
    
    NSString *strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"havingDetail_app_having.im"];
    
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager POST:strURl parameters:muDicParameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
        self.dicData = [dicInfo objectForKey:@"data"];
        
        
        if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
            
            self.dicData = [dicInfo objectForKey:@"data"];
            
            self.isFocus = self.dicData[@"isFocus"];
            self.isZan = self.dicData[@"isZan"];
            if ([self.isFocus isEqualToString:@"是"]) {
                [self.collectButton setImage:[UIImage imageNamed:@"评论点赞图标"] forState:UIControlStateNormal];
            }else
                [self.collectButton setImage:[UIImage imageNamed:@"资讯-点赞"] forState:UIControlStateNormal];
            
            if ([self.isZan isEqualToString:@"是"]) {
                self.zanButton.imageView.image = [UIImage imageNamed:@"点赞-2"];
            }else
                self.zanButton.imageView.image = [UIImage imageNamed:@"点赞-1"];
            
            if ([USER_DEFAULTS objectForKey:@"userid"] != nil) {
                [self.loveData addObserver:self forKeyPath:@"focusNumber" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:@"1"];
                [self.loveData addObserver:self forKeyPath:@"isfocus" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:@"2"];
                
            }
        }
        
        
        self.commentsList = [NSMutableArray arrayWithArray:self.dicData[@"commentsList"]];
        
        if (self.commentsList.count == 10) {
            self.tableview.mj_footer.hidden = NO;
        }else {
            self.tableview.mj_footer.hidden = YES;
        }
        
        //加载web页面
        [self loadWebView];
        
        
        [self hideBubble];
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

       [self showSingleIconBubble:error.localizedDescription];

    }];
    
}


//- (IBAction)clickPinglunBtn {
//    self.pagge = 1;
//    PinLunVC * pVC = [[PinLunVC alloc]init];
//    pVC.resId = self.projectId;
//    pVC.str = @"commentHaving_app_action.im.lensum";
//    [self.navigationController pushViewController:pVC animated:YES];
//}
//跳转到品论区
- (IBAction)jumpPinLun {
    
    [self.webView.scrollView setContentOffset:CGPointMake(0 ,self.didWebHeight - self.view.height + self.tableview.height) animated:YES];
}
#pragma mark -发评论
- (IBAction)sendPinglun:(UITextField *)sender {
    if (sender.text.length != 0) {
        if ([USER_DEFAULTS objectForKey:@"userid"]!=nil) {
//            [self.sender becomeFirstResponder];
            
            NSMutableDictionary *muDicParameters = [NSMutableDictionary dictionary];
            //token=验证用户&resId=资源id&content=内容&userId=用户id&userName=用户名称
            [muDicParameters setObject:self.projectId forKey:@"resId"];//资源id
            [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"userid"] forKey:@"userId"];
            [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"token"] forKey:@"token"];//验证用户
            [muDicParameters setObject:sender.text forKey:@"content"];
            [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"account"] forKey:@"userName"];
            
            NSString *strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"commentHaving_app_action.im.lensum"];
            AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
            
            [manager POST:strURl parameters:muDicParameters progress:^(NSProgress * _Nonnull uploadProgress) {
                
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
                NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
//                NSLog(@"%@",dicInfo);
                if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
                    self.commentsList = [NSMutableArray arrayWithArray:[dicInfo objectForKey:@"data"]];
                    
                    sender.text = @"";

                    [self showRightWithTitle:[dicInfo objectForKey:@"msg"] autoCloseTime:2];
                }else {

                    [self showSingleIconBubble:[dicInfo objectForKey:@"msg"]];
                }
                
                [self.tableview reloadData];
                
//                [self.textField resignFirstResponder];
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

                [self showSingleIconBubble:error.localizedDescription];

            }];
        }else {
            //登录
            UIStoryboard *LoginAndRegister = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            UINavigationController *loginNAV = [LoginAndRegister instantiateViewControllerWithIdentifier:@"LoginNav"];
            [self presentViewController:loginNAV animated:YES completion:nil];
        }
    }
    
    
    
}
//放弃第一响应者
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
    [self.textField resignFirstResponder];
}


#pragma mark - 获取跟多评论
-(void)getMorePingLun{
    
    NSMutableDictionary *muDicParameters = [NSMutableDictionary dictionary];
    //page=页码&projectId=项目id
    [muDicParameters setObject:self.projectId forKey:@"id"];
    [muDicParameters setObject:[NSString stringWithFormat:@"%ld",self.pagge] forKey:@"page"];
    
    NSString *strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"manyComentHaving_app_having.im"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:strURl parameters:muDicParameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
//        NSLog(@"dicInfo:%@",dicInfo);
//        
//        NSLog(@"%@",dicInfo);
        if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
            
            NSArray *aryInff = [dicInfo objectForKey:@"data"][@"record"];
            
            for (int i = 0; i<aryInff.count; i++) {
                [self.commentsList addObject:aryInff[i]];
                
            }
           
            if (aryInff.count == 10) {
                self.tableview.mj_footer.hidden = NO;
            }else {
                self.tableview.mj_footer.hidden = YES;
            }
            
            
            [self.tableview reloadData];
            
            
        }else {

            [self showSingleIconBubble:[dicInfo objectForKey:@"msg"]];

        }
        
        [self.tableview.mj_footer endRefreshing];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self.tableview.mj_footer endRefreshing];

        [self showSingleIconBubble:error.localizedDescription];

    }];
}


#pragma  mark - 点赞
- (IBAction)likeButtonAction:(UIButton *)sender {
    if ([USER_DEFAULTS objectForKey:@"userid"]!=nil) {

        NSMutableDictionary *muDicParameters = [NSMutableDictionary dictionary];
        //token=验证用户&userId=用户id&resId=资源id&resType=资源类型（1-项目 2-活动 3-服务 4-资金 5-招聘求职）
        [muDicParameters setObject:_projectId forKey:@"resId"];//资源id
        [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"userid"] forKey:@"userId"];
        [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"token"] forKey:@"token"];//验证用户
        
        NSString *strURl = @"";
        if ([self.isZan isEqualToString:@"否"]) {
            strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"zanResources_app_action.im.lensum"];
        }else {
            strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"zanResourcesCancel_app_action.im.lensum"];
        }
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        [manager POST:strURl parameters:muDicParameters progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
   
            if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
    
                if ([self.isZan isEqualToString:@"否"]) {
                    self.zanButton.imageView.image = [UIImage imageNamed:@"点赞-2"];
                    self.isZan = @"是";
                    
                }else {
                    self.zanButton.imageView.image = [UIImage imageNamed:@"点赞-1"];
                    self.isZan = @"否";
                    
                }

                [self showRightWithTitle:dicInfo[@"msg"] autoCloseTime:2];
                
            }else{

                [self showSingleIconBubble:dicInfo[@"msg"]];
            
            }
            

        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

            [self showSingleIconBubble:error.localizedDescription];

        }];
    }else {
        //登录
        UIStoryboard *LoginAndRegister = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        UINavigationController *loginNAV = [LoginAndRegister instantiateViewControllerWithIdentifier:@"LoginNav"];
        [self presentViewController:loginNAV animated:YES completion:nil];
    }

}

#pragma mark - 收藏
- (IBAction)collectButtonAction:(UIButton *)sender {
    if ([USER_DEFAULTS objectForKey:@"userid"]!=nil) {
        sender.selected = !sender.selected;
        NSLog(@"self.isFocus:%@",self.isFocus);
        NSMutableDictionary * dic = [NSMutableDictionary dictionary];
        dic[@"userId"] = [USER_DEFAULTS objectForKey:@"userid"];
        dic[@"token"] = [USER_DEFAULTS objectForKey:@"token"];
        dic[@"resId"] = self.projectId;
        dic[@"resType"] = @(6);
        NSLog(@"dic:%@",dic);
        NSString *strURL = @"";
        if ([self.isFocus isEqualToString:@"否"]) {
            strURL = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"focusResources_app_action.im.lensum"];

        }else{
            strURL = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"focusResourcesCancel_app_action.im.lensum"];
                    }
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        [manager POST:strURL parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
//            NSLog(@"dicINFO:%@",dicInfo);
            if ([dicInfo[@"result"] integerValue] == 1) {
                if ([self.isFocus isEqualToString:@"否"]) {
                    [self.collectButton setImage:[UIImage imageNamed:@"评论点赞图标"] forState:UIControlStateNormal];
                    self.isFocus = @"是";
                }else{
                    [self.collectButton setImage:[UIImage imageNamed:@"资讯-点赞"] forState:UIControlStateNormal];
                    self.isFocus =@"否";
                }

            }
            if ([dicInfo[@"result"] integerValue] == 2) {
                if ([self.isFocus isEqualToString:@"否"] ) {
                    self.isFocus =@"否";
                }else{
                    self.isFocus = @"是";
                }
                
            }

        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

            [self showSingleIconBubble:@"网络连接错误"];
        }];
        
        

    }else{
        //登录
        UIStoryboard *LoginAndRegister = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        UINavigationController *loginNAV = [LoginAndRegister instantiateViewControllerWithIdentifier:@"LoginNav"];
        [self presentViewController:loginNAV animated:YES completion:nil];
    }
    
    
}

#pragma mark - 分享
- (IBAction)shareButtonAction:(UIButton *)sender {
    
    if (self.dicData[@"description"] || self.javaScriptString.length != 0) {
        NSLog(@"%@",self.dicData[@"description"]);
        [ShareMsg shareMsgBOOLType:NO titleStr:self.dicData[@"title"] contentStr:self.javaScriptString urlStr:self.dicData[@"description"] imageAry:nil];
    }
    

    
}



#pragma mark - 评论tableView



-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
        return self.commentsList.count + 1;
    
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    
    PinLunCell *cell = [self tableView:self.tableview cellForRowAtIndexPath:indexPath];
    
    if (indexPath.row == 0) {
        return 50;
    }else{
        //设置cell自适应高度
    
    UILabel *descLabel = [[UILabel alloc]init];
    
    descLabel.text = self.commentsList[indexPath.row-1][@"content"];
    descLabel.numberOfLines = 0;
    descLabel.font = [UIFont systemFontOfSize:14];
    CGSize constraint = CGSizeMake(screenW-16, 2000.0f);
    CGSize size = [descLabel.text sizeWithFont:descLabel.font constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
    
        self.tableview.height = self.tableview.contentSize.height;
        
        self.webView.scrollView.contentInset = UIEdgeInsetsMake(self.numheight - 50, 0, self.tableview.height, 0);
   
        return cell.frame.size.height+size.height-12;
    
    }
    
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //注册
    UINib *nib = [UINib nibWithNibName:@"PinLunCell" bundle:nil];
    [self.tableview registerNib:nib forCellReuseIdentifier:PinLun];
    
    PinLunCell *cell = [self.tableview dequeueReusableCellWithIdentifier:PinLun];
    if (!cell) {
        cell = [[PinLunCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:PinLun];
    }
    
    
    
    
    if (indexPath.row == 0) {
        
        UITableViewCell *cellLe = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:PinLun];
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 14, 4, 22)];
        
        
        view.backgroundColor = [UIColor colorWithRed:67.0/255.0 green:177.0/255.0 blue:241.0/255.0 alpha:1];
        [cellLe addSubview:view];
        cellLe.textLabel.text = @"评论";
        cellLe.userInteractionEnabled = NO;
        return cellLe;
    }else{
    
        cell.posiTion.text = self.commentsList[indexPath.row-1][@"posiTion"];
        if ([self.commentsList[indexPath.row-1][@"posiTion"] isEqualToString:@"null"]) {
            cell.posiTion.text = @"";
        }
        [cell.headPhotoImageView sd_setImageWithURL:self.commentsList[indexPath.row-1][@"headPhoto"] placeholderImage:[UIImage imageNamed:@"project_detail_heder_normal"]];
        
        cell.headPhotoImageView.layer.masksToBounds = YES;
        cell.headPhotoImageView.layer.cornerRadius = 23.0f;
        
        cell.userName.textColor = [UIColor colorWithRed:23.0/255.0 green:176.0/255.0 blue:217.0/255.0 alpha:1];
        if ([self.commentsList[indexPath.row-1][@"commentUsername"] isEqualToString:@"null"] || [self.commentsList[indexPath.row-1][@"commentUsername"] isEqualToString:@""]) {
                cell.userName.text = self.commentsList[indexPath.row-1][@"commentAccount"];
        }else{
                cell.userName.text = self.commentsList[indexPath.row-1][@"commentUsername"];
        }
        
        NSDate *date = [CustomExcetion dateFromString:self.commentsList[indexPath.row-1][@"createTime"]];
        cell.timeLabel.text = [CustomExcetion prettyDateWithReference:date];
    
        cell.companyUserName.text = [UsedTool userType:self.commentsList[indexPath.row-1][@"userType"] companyName:self.commentsList[indexPath.row-1][@"companyName"] userAddress:self.commentsList[indexPath.row-1][@"userAddress"]];
        //认证
        cell.isAuthState.hidden = [UsedTool authStateImageViewHidden:self.commentsList[indexPath.row-1][@"authState"]];
        //会员图标
        cell.authStateImageView.image = [UsedTool setVipimage:self.commentsList[indexPath.row-1][@"vipLevel"]];
        CGSize sizeUserName = [cell.userName sizeThatFits:CGSizeMake(MAXFLOAT, 21)];
        CGSize sizePosition = [cell.posiTion sizeThatFits:CGSizeMake(MAXFLOAT, 21)];
        //名字长度控制
        if (sizePosition.width == 0) {
            if (sizeUserName.width > 170.0f) {
                cell.userNameConstraint.constant = 170.0f;
            }else{
                cell.userNameConstraint.constant = sizeUserName.width;
            }
        }else{
            if ((sizeUserName.width + sizePosition.width) <= 170.0f) {
                cell.userNameConstraint.constant = sizeUserName.width;
                cell.posiTionConstraint.constant = sizePosition.width;
            }else{
                
                if (sizeUserName.width >110.0f) {
                    cell.userNameConstraint.constant = 110.0f;
                }else{
                    cell.userNameConstraint.constant = sizeUserName.width;
                }
                if (sizePosition.width > 60.0f) {
                    cell.posiTionConstraint.constant = 60.0f;
                }else{
                    cell.posiTionConstraint.constant = sizePosition.width;
                }
            }
        }
        cell.commentContent.text = self.commentsList[indexPath.row-1][@"content"];
        return cell;
    }
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //取消选中状态
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;

}



@end
